<template>
  <div class="scene-swiper-container">
    <el-scrollbar ref="scrollbarRef">
      <div class="scene_view_page" 
           @mousedown="startDrag" 
           @mousemove="onDrag" 
           @mouseup="endDrag"
           @mouseleave="endDrag">
        <div
          v-for="viewItem in curFormSceneList"
          :key="viewItem.id"
          class="scene_view_item"
          :class="{ scene_view_item_active: viewItem.id == curSceneId }"
          @click="handleSceneClick(viewItem.id)"
          :title="viewItem.title"
        >
          <img 
            :data-src="getCutImg(viewItem.thumbUrl || viewItem.VRImg)" 
            src=""
            class="lazy-image"
            alt="" 
            draggable="false"
            ref="lazyImages">
          <span class="scene-tit">{{ viewItem.title }}</span>
        </div>
      </div>
    </el-scrollbar>

    <!-- 场景分类 -->
    <div class="scene-type" v-if="model == 'pc'">
      <div class="type-item" 
        v-for="(item, index) in firstSceneType" 
        :key="index" 
        :class="curFormSceneId == item.id ? 'type-item-checked' : ''"
        @click="handleCurFormSceneTypeChange(item.id)">
        {{item.title}}
      </div>
    </div>
    
  </div>
</template>
<script setup>
import { ref, toRefs, defineProps, defineEmits, watch, onMounted, nextTick, onUnmounted } from 'vue'
import store from '@/store';

const props = defineProps({
  model:String,
  sceneData:Object,
  curSceneId:String || Number,
})
const { sceneData, curSceneId, model } = toRefs(props)
const sceneTree = ref(sceneData.value.sceneTree)
const twoDimensionalSceneList = ref() //幻灯片二维数组
const emit = defineEmits(["onClickChangeScene"])
const firstSceneType = ref(sceneTree.value[0].children)

const curFormSceneList = ref([])
const curFormSceneId = ref(null)
// 选择场景类型 获取当前场景分类列表
const handleCurFormSceneTypeChange = (id) => {
  curFormSceneId.value = id
  curFormSceneList.value = []
  getCurFormSceneByPid(sceneTree.value, id)
  getSceneSwipe()
  emit('onClickChangeScene',curFormSceneList.value[0].id)
}
// 递归获取列表 本地
const getCurFormSceneByPid = (arr, pid, flag = false) => {
  arr.forEach(item => {
    if(item.id == pid || flag){
      curFormSceneList.value = curFormSceneList.value.concat(item.sceneList)
      if(item.children?.length > 0){
        getCurFormSceneByPid(item.children, pid, true)
      }
    }else if(item.children?.length > 0){
      getCurFormSceneByPid(item.children, pid)
    }
  })
}
// getCurFormSceneByPid(sceneTree.value, '0')

//场景轮播图
const getSceneSwipe = async () => {
  twoDimensionalSceneList.value = []
  let count = model.value == 'pc' ? 7 : 3
  for (let i = 0; i < curFormSceneList.value.length; i += count) {
    twoDimensionalSceneList.value.push(curFormSceneList.value.slice(i, i + count))
  }
}
getSceneSwipe()

const getCutImg = (filename) => {
  let nameWithoutExtension = filename.slice(0, -4);
  // 拼接新的文件名
  let newFilename
  if(store.state.VR.isRealTest){
    newFilename = nameWithoutExtension + '_1000_0_2500' + '.jpg';
  }else{
    newFilename = nameWithoutExtension + '' + '.jpg';
  }
  return newFilename;
}

const initialIndex = ref(0)
const carousel = ref()
// 监听场景图id变化
watch(() => sceneData.value.curSceneId,() => {
  handleCarouselChange()
},{deep:true})
// 场景图变化 切换幻灯片轮播
const handleCarouselChange = (val) => {
  if(carousel.value && val){
    carousel.value.setActiveItem(val)
    return
  }
  // 获取当前场景图的幻灯片二维数组索引
  initialIndex.value = twoDimensionalSceneList.value.findIndex(curList => {
    let is = curList.findIndex(item => {
      return item.id == sceneData.value.curSceneId
    })
    return is == -1 ? false : true
  }) 
  // 如果要跳转的场景图不在当前场景分类下，找到他的场景分类列表
  setTimeout(() => {
    if(carousel.value && initialIndex.value != -1) carousel.value.setActiveItem(initialIndex.value)
  }, 0);
}
onMounted(() => {
  // 默认选中第一个场景类型
  handleCurFormSceneTypeChange(firstSceneType.value[0].id)
  observeImages()
})
// 暴露方法
defineExpose({
  handleCurFormSceneTypeChange
})

const scrollbarRef = ref(null)
const isDragging = ref(false)
const startX = ref(0)
const scrollLeft = ref(0)
const hasMoved = ref(false) // 添加一个变量来追踪是否发生了移动

const handleSceneClick = (id) => {
  if (!hasMoved.value) {
    emit('onClickChangeScene', id)
  }
}

const startDrag = (e) => {
  isDragging.value = true
  hasMoved.value = false
  startX.value = e.pageX
  scrollLeft.value = scrollbarRef.value.wrap$.scrollLeft
}

const onDrag = (e) => {
  if (!isDragging.value) return
  e.preventDefault()
  const x = e.pageX
  const walk = startX.value - x
  if (Math.abs(walk) > 5) { // 只有移动距离超过5像素才认为是拖拽
    hasMoved.value = true
  }
  scrollbarRef.value.wrap$.scrollLeft = scrollLeft.value + walk
}

const endDrag = () => {
  isDragging.value = false
}

// 懒加载相关
const lazyImages = ref([])
let observer = null

const initIntersectionObserver = () => {
  observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target
        img.src = img.dataset.src
        observer.unobserve(img)
      }
    })
  }, {
    root: null,
    rootMargin: '50px', // 提前50px开始加载
    threshold: 0.1
  })
}

const observeImages = () => {
  nextTick(() => {
    if (!observer) {
      initIntersectionObserver()
    }
    
    // 获取所有懒加载图片
    const images = document.querySelectorAll('.lazy-image')
    images.forEach(img => {
      observer.observe(img)
    })
  })
}

// 在场景列表更新时重新观察图片
watch(() => curFormSceneList.value, () => {
  observeImages()
}, { deep: true })

// 组件销毁时清理 observer
onUnmounted(() => {
  if (observer) {
    observer.disconnect()
    observer = null
  }
})
</script>
<style lang="scss" scoped>
.scene-swiper-container{
  padding: 0 20px;
}
.scene_view_page {
  display: flex;
  align-items: center;
  height: 100%;
  margin: 10px 0 15px 0;
  cursor: grab;
  user-select: none; // 禁止选择文本
  &:active {
    cursor: grabbing;
  }
}
.scene_view_item:last-child {
  margin-right: 0;
}
.scene_view_item .scene_image {
  width: 120px;
  height: 70px;
}
.scene_view_item {
  width: 125px;
  height: 82px;
  margin-right: 15px;
  background-color: rgba(0, 0, 0, .8);
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  border: 2px solid transparent;
  flex-shrink: 0;
  .scene-tit {
    position: absolute;
    bottom: -2px;
    left: 50%;
    transform: translateX(-50%);
    text-align: center;
    font-size: 14px;
    font-weight: 600;
    color: #fff;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100px;
    user-select: none; // 禁止选择文本
  }
  img {
    max-width: 100%;
    max-height: 100%;
    pointer-events: none;
    user-select: none;
    -webkit-user-drag: none;
    transition: opacity 0.3s; // 添加淡入效果
    
    &.lazy-image {
      opacity: 0;
      
      &[src^="data:image"] {
        background: rgba(0, 0, 0, 0.1); // 加载前的占位背景
      }
      
      &[src^="http"], &[src^="/"] {
        opacity: 1;
      }
    }
  }
  &:hover{
    cursor: pointer;
    border: 2px solid #fff;
  }
}
.scene_view_item_active {
  border: 2px solid #fff;
}
.scene-type{
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  .type-item{
    margin: 0 10px;
    color: #fff;
    overflow: hidden;
    white-space: nowrap;
    display: inline-block;
    text-align: center;
    opacity: .6;
    margin-bottom: 5px;
    cursor: pointer;
    border: 1px solid #999;
    background: rgba(0, 0, 0, .4);
    border-radius: 13px;
    box-sizing: border-box;
    padding: 1px 12px;
  }
  .type-item-checked{
    border: 2px solid #fff;
    opacity: 1;
  }
}
::v-deep(.el-empty){
  .el-empty__image{
    display: none;
  }
}
@media screen and (max-width: 1024px) {
  .scene_view_item {
    width: 108px;
    height: 80px;
    margin-right: 10px;
    margin-bottom: 10px;
  }
  .scene_view_item .scene-tit {
    width: 100px;
  }
  .scene_view_item img {
    width: 100px;
    height: 56px;
  }
}
</style>
